886D - Restoration of string - CodeForces Solution


constructive algorithms graphs implementation *2000

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
 
char s[maxn];
char ans[30];
int cnt[26];
int m0[26],d[26],mp[26];
int n,anslen;
 
int main()
{
    scanf("%d",&n);
    memset(mp,0xFF,sizeof(mp));
    for (int i=0;i<n;i++)
    {
        scanf("%s",s);
        int len=strlen(s);
        memset(cnt,0,sizeof(cnt));
        for (int j=0;j<len;j++)
        {
            if (cnt[s[j]-'a']++)
            {
                puts("NO");
                return 0;
            }
            if (j<len-1)
            {
                if (mp[s[j]-'a']!=-1 && mp[s[j]-'a']!=s[j+1]-'a')
                {
                    puts("NO");
                    return 0;
                }
                if (mp[s[j]-'a']==-1) mp[s[j]-'a']=s[j+1]-'a',d[s[j+1]-'a']++;
            }
        }
        m0[s[0]-'a']=1;
    }
    for (int i=0;i<26;i++) if (d[i]) m0[i]=0;
    memset(cnt,0,sizeof(cnt));
    for (int i=0;i<26;i++)
        if (m0[i])
        {
            int t=i;
            while (t!=-1)
            {
                if (++cnt[t]>1)
                {
                    puts("NO");
                    return 0;
                }
                ans[anslen++]=t+'a';
                t=mp[t];
                if (t!=-1) d[t]--;
            }
        }
    for (int i=0;i<26;i++) if (d[i])
    {
        puts("NO");
        return 0;
    }
    printf("%s\n",ans);
    return 0;
}


Comments

Submit
0 Comments
More Questions

148A - Insomnia cure
1650A - Deletions of Two Adjacent Letters
1512A - Spy Detected
282A - Bit++
69A - Young Physicist
1651A - Playoff
734A - Anton and Danik
1300B - Assigning to Classes
1647A - Madoka and Math Dad
710A - King Moves
1131A - Sea Battle
118A - String Task
236A - Boy or Girl
271A - Beautiful Year
520B - Two Buttons
231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters